package com.bookrecommendation.client.facebook;

import com.bookrecommendation.client.GWTEntryPoint;
import com.bookrecommendation.client.database.RequestListUserBook;
import com.bookrecommendation.client.database.RequestSaveUserBook;
import com.bookrecommendation.client.facebook.sdk.FBCore;
import com.bookrecommendation.client.facebook.sdk.JSOModel;
import com.bookrecommendation.client.web.PopupBooks;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class FacebookFriendBooks {

	public FacebookFriendBooks(FBCore fbCore, final String userID,
			final String userName, final boolean me) {

		fbCore.api("/" + userID + "/books",
				new AsyncCallback<JavaScriptObject>() {

					@Override
					public void onFailure(Throwable caught) {

					}

					@Override
					public void onSuccess(JavaScriptObject result) {

						JSOModel jso = result.cast();
						JsArray array = jso.getArray("data");

						if (array.length() > 0) {

							String booksIds = "";

							for (int i = 0; i < array.length(); i++) {

								JSOModel j = array.get(i).cast();

								String id = j.get("id");

								String name = j.get("name");

								booksIds += id + ",";

								if (me) {

									GWTEntryPoint.facebookUserBooks.put(id, 0);

								} else {

									if (GWTEntryPoint.facebookUserBooks.get(id) != null) {

										GWTEntryPoint.facebookUserBooks.put(id,
												GWTEntryPoint.facebookUserBooks
														.get(id) + 1);

									} else {

										GWTEntryPoint.facebookFriendsBooks.put(
												id,
												GWTEntryPoint
														.addValue(
																GWTEntryPoint.facebookFriendsBooks,
																id));
									}
								}
							}

							RequestSaveUserBook.sendPostRequest(userID,
									userName, booksIds);
						}

						if (me) {

							RequestListUserBook.get();
						}

						GWTEntryPoint.friendsSearched++;

						if (GWTEntryPoint.friendsAmount != 0
								&& GWTEntryPoint.friendsSearched >= (GWTEntryPoint.friendsAmount - 1)) {

							new PopupBooks();
						}
					}
				});
	}
}
